//
//  HMOauthViewController.swift
//  GuoGuo
//
//  Created by 艾小新 on 16/8/4.
//  Copyright © 2016年 xiaoxin. All rights reserved.
//

import UIKit
import SVProgressHUD

// MARK: - 应用程序信息
 let WB_APPKEY = "3633420896"
 let WB_APPSECRET = "542f0683e5a688f693a55916915bd4f1"
 let WB_REDIRECTURI = "http://www.baidu.com/"


class HMOauthViewController: UIViewController {
    


    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        
        view = webView
        
        // 设置左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: nil, title: "返回", target: self, action: #selector(HMOauthViewController.returnBtn))
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: nil, title: "自动填充", target: self, action: #selector(HMOauthViewController.autoBtn))
        
    }
    // 返回
    @objc private func returnBtn() {
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    // 自动填充（调用JS）
    @objc private func autoBtn() {
        
        let jsString = "document.getElementById('userId').value='18547116395';document.getElementById('passwd').value='q11111'"
        // 让当前 webView执行以上这句js代码
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
    
    // MARK: -懒加载webView
    private lazy var webView: UIWebView = {
       
        let v = UIWebView()
        
        let loc = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REDIRECTURI)"
        let url = NSURL(string: loc)
        
        v.loadRequest(NSURLRequest(URL: url!))
        
        v.delegate = self
        
        return v
    }()
    

}

// MARK: webView代理方法
extension HMOauthViewController: UIWebViewDelegate {
    
    // 这个方法就是加载网页的时候会调用
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let req = request.URL?.absoluteString else {
            
            return true
        }

        if req.hasPrefix(WB_REDIRECTURI) {
            
            // 这里拿code
            let code = request.URL?.query?.substringFromIndex("code=".endIndex)
            
            HMUserLoginViewModel.sharedUserLoginViewModel.loadToken(code!, callback: { (isSuccess) in
                
                if !isSuccess {
                    // 登录失败
                    SVProgressHUD.showErrorWithStatus("验证失败")
                }else {
                    
                    print("跳转到WelCome页面·")
                    
                    NSNotificationCenter.defaultCenter().postNotificationName(HMLogonViewChangeNotification, object: self)
                    
                    self.returnBtn()
                }

            })
            
            return false
            
            
        }
        return true
        
    }
    
    
}
